package com.lixin.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 生产者与消费者模拟（多个线程）
public class PC {

    private int num = 0;
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    // 生产者
    public void increment() {
        lock.lock();
        try {
            while (num != 0) {
                System.out.println(Thread.currentThread().getName() + "等待中...");
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName() + " -> " + num);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    // 消费者
    public void decrement() {
        lock.lock();
        try {
            while (num == 0) {
                System.out.println(Thread.currentThread().getName() + "等待中...");
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName() + " -> " + num);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
